<template>
	<view class="container">
		<!-- 顶部标题 -->
		<view class="header">
			<text class="title">教师签到系统</text>
			<text class="subtitle">{{ currentTime }} {{ currentDate }}</text>
			<text class="teacher-name">{{ teacherInfo.name }}</text>
		</view>

		<!-- 打卡状态卡片 -->
		<view class="status-card" :class="statusCardClass">
			<view class="status-icon">
				<uni-icons :type="statusIconType" size="60" :color="statusIconColor"></uni-icons>
			</view>
			<text class="status-text">{{ statusMessage }}</text>
			<text class="check-info" v-if="checkInfo">{{ checkInfo }}</text>
			<text class="time-range">{{ timeRangeText }}</text>
		</view>

		<!-- 签到码输入框 -->
		<view class="code-input-container" v-if="showCodeInput">
			<view class="code-input">
				<view class="code-digit" v-for="(digit, index) in codeDigits" :key="index"
					:class="{'active': currentDigit === index}">
					{{ digit || ' ' }}
				</view>
			</view>
			<text class="hint-text" v-if="hintText">{{ hintText }}</text>
		</view>

		<!-- 数字键盘 -->
		<view class="keyboard" v-if="showCodeInput">
			<view class="keyboard-row">
				<view class="key" v-for="num in [1,2,3]" :key="num" @touchstart="onKeyPress(num)"
					@touchend="clearActiveKey" :class="{'active': activeKey === num}">
					{{ num }}
				</view>
			</view>
			<view class="keyboard-row">
				<view class="key" v-for="num in [4,5,6]" :key="num" @touchstart="onKeyPress(num)"
					@touchend="clearActiveKey" :class="{'active': activeKey === num}">
					{{ num }}
				</view>
			</view>
			<view class="keyboard-row">
				<view class="key" v-for="num in [7,8,9]" :key="num" @touchstart="onKeyPress(num)"
					@touchend="clearActiveKey" :class="{'active': activeKey === num}">
					{{ num }}
				</view>
			</view>
			<view class="keyboard-row">
				<view class="key delete" @touchstart="onKeyPress('backspace')" @touchend="clearActiveKey"
					:class="{'active': activeKey === 'backspace'}">
					<uni-icons type="backspace" size="36" color="#666"></uni-icons>
					<text>删除</text>
				</view>
				<view class="key" @touchstart="onKeyPress(0)" @touchend="clearActiveKey"
					:class="{'active': activeKey === 0}">
					0
				</view>
				<view class="key submit" @touchstart="!isCoolingDown && onKeyPress('submit')" @touchend="clearActiveKey"
					:class="{
                'active': activeKey === 'submit', 
                'disabled': codeDigits.join('').length !== 4 || !canCheckIn || isCoolingDown
              }">
					<text>确定</text>
				</view>
			</view>
		</view>

		<!-- 操作按钮 -->
		<view class="action-buttons">
			<button class="refresh-btn" @click="fetchTeacherCheck">
				<uni-icons type="refresh" size="20" color="#4D59FF"></uni-icons>
				<text>刷新状态</text>
			</button>
		</view>
	</view>
</template>
<script>
	import {
		globalVariable
	} from '../../configMy.js';

	export default {
		data() {
			return {
				currentTime: this.formatTime(new Date()),
				currentDate: this.formatDate(new Date()),
				codeDigits: ['', '', '', ''],
				currentDigit: 0,
				activeKey: null,
				checkStatus: '', // '', 'success', 'error', 'expired', 'warning'
				statusMessage: '正在获取打卡状态...',
				hintText: '',
				checkInfo: '',
				isSubmitting: false,
				isLoading: false,
				teacherInfo: {
					id: '',
					name: ''
				},
				checkRecord: null,
				timeInterval: null,
				canCheckIn: false,
				showCodeInput: false,
				checkType: 0, // 0: 未确定, 1: 上班打卡, 2: 下班打卡
				checkId: 0,
				isCoolingDown: false, // 新增：冷却状态
				coolDownTimer: null // 新增：冷却计时器
			};
		},
		computed: {
			statusCardClass() {
				return {
					'success': this.checkStatus === 'success',
					'error': this.checkStatus === 'error',
					'expired': this.checkStatus === 'expired',
					'warning': this.checkStatus === 'warning'
				};
			},
			statusIconType() {
				return {
					'success': 'checkmarkempty',
					'error': 'closeempty',
					'expired': 'clock',
					'warning': 'alert'
				} [this.checkStatus] || 'info';
			},
			statusIconColor() {
				return {
					'success': '#4CAF50',
					'error': '#F44336',
					'expired': '#FF9800',
					'warning': '#FFC107'
				} [this.checkStatus] || '#4D59FF';
			},
			timeRangeText() {
				if (this.checkType === 1) {
					return '上班打卡时间: 07:30 - 10:00';
				} else if (this.checkType === 2) {
					return '下班打卡时间: 17:30 - 22:00';
				}
				return '';
			}
		},
		onLoad(options) {
			// 从本地缓存获取老师数据
			const teacherData = uni.getStorageSync('teacherData');
			if (teacherData) {
				this.teacherInfo = {
					id: teacherData.teacherId,
					name: teacherData.name
				};
			} else {
				// 如果缓存中没有，使用传入的参数
				this.teacherInfo = {
					id: options.teacherId || '',
					name: options.teacherName || ''
				};
			}
			this.startTimeUpdater();
			this.fetchTeacherCheck();
		},
		onUnload() {
			this.stopTimeUpdater();
		},
		methods: {
			formatTime(date) {
				const hours = date.getHours().toString().padStart(2, '0');
				const minutes = date.getMinutes().toString().padStart(2, '0');
				const seconds = date.getSeconds().toString().padStart(2, '0');
				return `${hours}:${minutes}:${seconds}`;
			},
			formatDate(date) {
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				return `${year}-${month}-${day}`;
			},
			startTimeUpdater() {
				this.stopTimeUpdater();
				this.timeInterval = setInterval(() => {
					this.currentTime = this.formatTime(new Date());
				}, 1000);
			},
			stopTimeUpdater() {
				if (this.timeInterval) {
					clearInterval(this.timeInterval);
					this.timeInterval = null;
				}
			},
			async fetchTeacherCheck() {
				this.isLoading = true;
				this.statusMessage = '正在获取打卡状态...';
				this.showCodeInput = false;

				try {
					const res = await new Promise((resolve, reject) => {
						uni.request({
							url: `${globalVariable}/getTeacherCheck?teacherId=${this.teacherInfo.id}&date=${this.currentDate}`,
							method: 'GET',
							success: resolve,
							fail: reject
						});
					});

					if (res.data.status === 1) {
						this.checkRecord = res.data.data;
						this.checkId = res.data.data.id;
						this.updateCheckStatus();
					} else if (res.data.status === 2) {
						this.checkStatus = 'warning';
						this.statusMessage = '上班未打卡';
						this.checkInfo = '请先完成上班打卡';
						this.checkType = 1;
						this.checkTimeRange();
					} else {
						this.checkStatus = 'error';
						this.statusMessage = '获取打卡信息失败';
						this.showHint(res.data.message || '请稍后重试');
					}
				} catch (error) {
					console.error('获取打卡信息出错:', error);
					this.checkStatus = 'error';
					this.statusMessage = '网络错误';
					this.showHint('请检查网络连接');
				} finally {
					this.isLoading = false;
				}
			},
			checkTimeRange() {
				const now = new Date();
				const hours = now.getHours();
				const minutes = now.getMinutes();
				const currentTime = hours * 60 + minutes;

				// 上午打卡时间 07:30-10:00 (450-600分钟)
				const morningStart = 7 * 60 + 30;
				const morningEnd = 10 * 60;

				// 下午打卡时间 17:30-22:00 (1050-1320分钟)
				const afternoonStart = 17 * 60 + 30;
				const afternoonEnd = 22 * 60;

				if (this.checkType === 1) {
					if (currentTime >= morningStart && currentTime <= morningEnd) {
						this.canCheckIn = true;
						this.showCodeInput = true;
						this.statusMessage = '请完成上班打卡';
					} else if (currentTime > morningEnd) {
						this.canCheckIn = false;
						this.showCodeInput = false;
						this.checkStatus = 'expired';
						this.statusMessage = '已错过上班打卡时间';
						this.checkInfo = '今日无法再进行打卡';
					}
				} else if (this.checkType === 2) {
					if (currentTime >= afternoonStart && currentTime <= afternoonEnd) {
						this.canCheckIn = true;
						this.showCodeInput = true;
						this.statusMessage = '请完成下班打卡';
					} else if (currentTime > afternoonEnd) {
						this.canCheckIn = false;
						this.showCodeInput = false;
						this.checkStatus = 'expired';
						this.statusMessage = '已错过下班打卡时间';
					}
				}
			},
			updateCheckStatus() {
				if (!this.checkRecord) {
					this.checkStatus = 'warning';
					this.statusMessage = '今日未打卡';
					this.checkType = 1;
					this.checkTimeRange();
					return;
				}

				this.checkId = this.checkRecord.id;

				if (!this.checkRecord.checkInTime) {
					this.checkStatus = 'warning';
					this.statusMessage = '上班未打卡';
					this.checkInfo = '请先完成上班打卡';
					this.checkType = 1;
					this.checkTimeRange();
					return;
				}

				if (!this.checkRecord.checkOutTime) {
					this.checkStatus = 'warning';
					this.statusMessage = '下班未打卡';
					this.checkInfo = `上班打卡时间: ${this.checkRecord.checkInTime}`;
					this.checkType = 2;
					this.checkTimeRange();
					return;
				}

				this.checkStatus = 'success';
				this.statusMessage = '今日打卡已完成';
				this.checkInfo = `上班: ${this.checkRecord.checkInTime}\n下班: ${this.checkRecord.checkOutTime}`;
				this.showCodeInput = false;
			},
			onKeyPress(key) {
				if (key === 'submit' && this.isSubmitting) return;

				this.activeKey = key;

				if (key === 'backspace') {
					if (this.currentDigit > 0) {
						this.codeDigits[this.currentDigit - 1] = '';
						this.currentDigit--;
					}
				} else if (key === 'submit') {
					if (this.codeDigits.join('').length === 4 && this.canCheckIn) {
						this.submitCode();
					}
				} else if (typeof key === 'number' && this.currentDigit < 4) {
					this.codeDigits[this.currentDigit] = key.toString();
					if (this.currentDigit < 3) {
						this.currentDigit++;
					}
				}

				this.hintText = '';
			},
			clearActiveKey() {
				this.activeKey = null;
			},
			// 新增冷却方法
			startCoolDown() {
				this.isCoolingDown = true;
				// 清除之前的计时器（如果有）
				if (this.coolDownTimer) {
					clearTimeout(this.coolDownTimer);
				}
				// 设置3秒后解除冷却
				this.coolDownTimer = setTimeout(() => {
					this.isCoolingDown = false;
				}, 3000);
			},

			async submitCode() {
				if (this.isSubmitting || !this.canCheckIn || this.isCoolingDown) return;

				const code = this.codeDigits.join('');
				if (code.length !== 4) {
					this.showHint('请输入完整的4位签到码');
					return;
				}

				this.isSubmitting = true;
				this.statusMessage = '正在验证签到码...';
				this.startCoolDown(); // 开始冷却

				try {
					const isValid = await this.validateCode(code);
					// const isValid = true;
					// console.log(isValid)
					if (isValid) {
						const success = await (this.checkType === 1 ? this.submitCheckIn() : this.submitCheckOut());

						if (success) {
							this.checkStatus = 'success';
							this.statusMessage = this.checkType === 1 ? '上班打卡成功！' : '下班打卡成功！';
							this.showHint('', 3000);
							setTimeout(() => {
								this.fetchTeacherCheck();
								this.resetForm();
							}, 3000);
						} else {
							this.checkStatus = 'error';
							this.statusMessage = '打卡提交失败';
							this.showHint('请重试或联系管理员');
						}
					} else {
						this.checkStatus = 'error';
						this.statusMessage = '签到码错误';
						this.showHint('请输入正确的签到码');
					}
				} catch (error) {
					console.error('打卡出错:', error);
					this.checkStatus = 'error';
					this.statusMessage = '网络错误';
					this.showHint('请检查网络连接');
				} finally {
					this.isSubmitting = false;
				}
			},
			async validateCode(code) {
				// 从本地缓存获取老师数据
				const teacherData = uni.getStorageSync('teacher');
				if (!teacherData || !teacherData.teacherId) {
					console.error('未获取到老师信息');
					return false;
				}

				return new Promise((resolve, reject) => {
					uni.request({
						url: `${globalVariable}/validateCheckInCode?teacherId=${teacherData.teacherId}&checkInCode=${code}&date=${this.currentDate}`,
						method: 'GET',
						success: (res) => {
							if (res.data && res.data.status === 1) {
								
								resolve(res.data.data);
							} else {
								uni.showToast({
									title:res.data.message
								})
								resolve(false);
							}
						},
						fail: (error) => {
							console.error('验证码验证失败:', error);
							reject(error);
						}
					});
				});
			},
			async submitCheckIn() {
				return new Promise((resolve, reject) => {
					const checkTime = this.formatTime(new Date());

					uni.request({
						url: `${globalVariable}/workTeacherCheck?teacherId=${this.teacherInfo.id}&name=${encodeURIComponent(this.teacherInfo.name)}&date=${this.currentDate}&checkInTime=${checkTime}&checkOutTime=`,
						method: 'POST',
						success: (res) => {
							if (res.data.status === 1) {
								this.checkId = res.data.data.id;
								resolve(true);
							} else {
								resolve(false);
							}
						},
						fail: reject
					});
				});
			},
			async submitCheckOut() {
				return new Promise((resolve, reject) => {
					const checkOutTime = this.formatTime(new Date());

					uni.request({
						url: `${globalVariable}/restTeacherCheck?id=${this.checkId}&checkOutTime=${checkOutTime}`,
						method: 'POST',
						success: (res) => {
							resolve(res.data.status === 1);
						},
						fail: reject
					});
				});
			},
			showHint(text, timeout = 2000) {
				this.hintText = text;
				if (timeout > 0) {
					setTimeout(() => {
						this.hintText = '';
					}, timeout);
				}
			},
			resetForm() {
				this.codeDigits = ['', '', '', ''];
				this.currentDigit = 0;
			}
		}
	};
</script>
<style lang="scss" scoped>
	/* 基础颜色定义 */
	$primary-color: #4D59FF;
	$success-color: #4CAF50;
	$error-color: #F44336;
	$warning-color: #FFC107;
	$expired-color: #FF9800;
	$text-color: #333;
	$text-light: #666;
	$text-lighter: #999;
	$border-color: #eee;
	$bg-color: #f8f9fa;
	$card-bg: #fff;
	$shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);

	.container {
		padding: 40rpx;
		background-color: $bg-color;
		min-height: 100vh;
		display: flex;
		flex-direction: column;
		font-family: 'PingFang SC', 'Helvetica Neue', Arial, sans-serif;
	}

	/* 顶部标题 */
	.header {
		text-align: center;
		margin-bottom: 40rpx;

		.title {
			font-size: 48rpx;
			font-weight: bold;
			color: $primary-color;
			display: block;
			margin-bottom: 10rpx;
		}

		.subtitle {
			font-size: 28rpx;
			color: $text-light;
			display: block;
			margin-bottom: 8rpx;
		}

		.teacher-name {
			font-size: 32rpx;
			color: $text-color;
			font-weight: 500;
		}
	}

	/* 状态卡片 */
	.status-card {
		background-color: $card-bg;
		border-radius: 24rpx;
		padding: 40rpx;
		margin-bottom: 40rpx;
		box-shadow: $shadow;
		text-align: center;
		transition: all 0.3s;

		&.success {
			background-color: rgba($success-color, 0.1);
			border-left: 8rpx solid $success-color;
		}

		&.error {
			background-color: rgba($error-color, 0.1);
			border-left: 8rpx solid $error-color;
		}

		&.warning {
			background-color: rgba($warning-color, 0.1);
			border-left: 8rpx solid $warning-color;
		}

		&.expired {
			background-color: rgba($expired-color, 0.1);
			border-left: 8rpx solid $expired-color;
		}

		.status-icon {
			margin-bottom: 20rpx;
		}

		.status-text {
			font-size: 32rpx;
			color: $text-color;
			font-weight: 500;
			display: block;
			margin-bottom: 10rpx;
		}

		.check-info {
			font-size: 26rpx;
			color: $text-light;
			display: block;
			margin: 20rpx 0;
			white-space: pre-line;
			line-height: 1.6;
		}

		.time-range {
			font-size: 24rpx;
			color: $text-light;
		}
	}

	/* 签到码输入框 */
	.code-input-container {
		margin-bottom: 60rpx;

		.code-input {
			display: flex;
			justify-content: center;
			margin-bottom: 20rpx;

			.code-digit {
				width: 100rpx;
				height: 120rpx;
				margin: 0 10rpx;
				border-bottom: 4rpx solid $border-color;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 56rpx;
				font-weight: bold;
				color: $primary-color;
				transition: all 0.3s;

				&.active {
					border-bottom-color: $primary-color;
				}
			}
		}

		.hint-text {
			display: block;
			text-align: center;
			font-size: 26rpx;
			color: $error-color;
			height: 40rpx;
		}
	}

	/* 数字键盘 */
	.keyboard {
		margin-bottom: 40rpx;

		.keyboard-row {
			display: flex;
			justify-content: center;
			margin-bottom: 20rpx;

			.key {
				width: 200rpx;
				height: 100rpx;
				margin: 0 10rpx;
				background-color: $card-bg;
				border-radius: 12rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 40rpx;
				font-weight: bold;
				color: $text-color;
				box-shadow: $shadow;
				transition: all 0.1s;

				&:active,
				&.active {
					background-color: $primary-color;
					color: white;
					transform: scale(0.95);
				}

				&.delete {
					background-color: #f5f5f5;
				}

				&.submit {
					background-color: $primary-color;
					color: white;

					&.disabled {
						background-color: #ccc;
						opacity: 0.7;
						pointer-events: none;
					}

					.loading {
						display: flex;
						justify-content: center;
						align-items: center;

						.loading-spinner {
							width: 30rpx;
							height: 30rpx;
							border: 4rpx solid rgba(255, 255, 255, 0.3);
							border-top-color: white;
							border-radius: 50%;
							animation: spin 1s linear infinite;
						}
					}
				}
			}
		}
	}

	/* 操作按钮 */
	.action-buttons {
		display: flex;
		justify-content: center;
		margin-top: 40rpx;

		.refresh-btn {
			background-color: transparent;
			border: 2rpx solid $primary-color;
			border-radius: 50rpx;
			color: $primary-color;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0 30rpx;
			height: 80rpx;
			font-size: 28rpx;

			uni-icons {
				margin-right: 10rpx;
			}

			&:active {
				background-color: rgba($primary-color, 0.1);
			}
		}
	}

	@keyframes spin {
		to {
			transform: rotate(360deg);
		}
	}
</style>